<template>
	<view class="container">
		<view class="form">
			<view class="form-item">
				<label>用户名:</label>
				<input v-model="username" type="text" placeholder="请输入用户名（至少3位）" />
				<text v-if="username.length < 3 && username.length > 0" class="error-tip">用户名至少3位</text>
			</view>
			<view class="form-item">
				<label>密码:</label>
				<input v-model="password" type="password" placeholder="请输入密码（至少6位）" />
				<text v-if="password.length < 6 && password.length > 0" class="error-tip">密码至少6位</text>
			</view>
			<view class="form-item">
				<label>姓名:</label>
				<input v-model="name" type="text" placeholder="请输入姓名" />
			</view>
			<view class="form-item">
				<label>学校:</label>
				<input v-model="school" type="text" placeholder="请输入学校" />
			</view>
			<view class="form-item">
				<label>学号:</label>
				<input v-model="studentId" type="text" placeholder="请输入学号" />
			</view>
			<button @click="register">注册</button>
			<view class="login-link" @click='login'>前往登录</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		Authregister
	} from '../../request/api.js';

	const username = ref('');
	const password = ref('');
	const name = ref('');
	const school = ref('');
	const studentId = ref('');

	const register = async () => {
		if (username.value.length < 3) {
			uni.showToast({
				title: '用户名至少3位',
				icon: 'none'
			});
			return;
		}
		if (password.value.length < 6) {
			uni.showToast({
				title: '密码至少6位',
				icon: 'none'
			});
			return;
		}
		if (username.value && password.value && name.value && school.value && studentId.value) {
			try {
				const res = await Authregister({
					username: username.value,
					password: password.value,
					name: name.value,
					school: school.value,
					studentId: studentId.value
				});
				uni.showToast({
					title: '注册成功',
					icon: 'success'
				});
				setTimeout(() => uni.redirectTo({
					url: '/pages/login/index'
				}), 1000)
			} catch (error) {
				uni.showToast({
					title: '注册失败，请重试',
					icon: 'none'
				});
			}
		} else {
			uni.showToast({
				title: '所有字段都必须填写',
				icon: 'none'
			});
		}
	};

	const login = () => {
		uni.navigateTo({
			url: '/pages/login/index'
		});
	};
</script>

<style scoped>
	.container {
		padding: 20px;
	}

	.form {
		margin-top: 50px;
	}

	.form-item {
		margin-bottom: 20px;
		position: relative;
	}

	.form-item label {
		display: block;
		margin-bottom: 5px;
	}

	.form-item input {
		width: 100%;
		padding: 10px 0px 10px 5px;
		border: 1px solid #ccc;
		border-radius: 5px;
	}

	.error-tip {
		color: red;
		font-size: 12px;
		position: absolute;
		bottom: 0;
		left: 0;
	}

	button {
		width: 100%;
		padding: 10px;
		background-color: #007aff;
		color: white;
		border: none;
		border-radius: 5px;
		cursor: pointer;
	}

	.login-link {
		text-align: center;
		margin-top: 10px;
		color: #007aff;
		text-decoration: underline;
		cursor: pointer;
	}
</style>